package com.liang.sql;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;
import org.json.JSONObject;
import com.google.common.collect.Maps;
import com.liang.kit.ReflectUtil;

public class SqlBuilder {

	private String tableName;
	private String uniqueKey;
	private static final SqlBuilder sqlBuilder=new SqlBuilder();
	
	public static SqlBuilder me(Class<?> clazz){
		sqlBuilder.setClazz(clazz);
		return sqlBuilder;
	}

	public void setClazz(Class<?> clazz){
		if(clazz.isAnnotationPresent(TableBind.class)){
			TableBind table=clazz.getAnnotation(TableBind.class);
			this.tableName=table.tableName();
			this.uniqueKey=table.uniqueKey();
			
		}else{
			this.tableName=clazz.getSimpleName();
			this.uniqueKey="id";
		}
	}
	public String buildInsertSql(Object obj) {
		try {
			System.out.println(new JSONObject(describe(obj)).toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		StringBuilder insert=new  StringBuilder("insert into "+tableName);
		return insert.toString();
	}

	public String buildUpdateSql(Object obj) {
		try {
			System.out.println(new JSONObject(describe(obj)).toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		StringBuilder update=new  StringBuilder("update");
		return update.toString();
	}

	public String buildDeleteSql(String id) {
		StringBuilder delete=new  StringBuilder("delete from "+tableName+" where "+uniqueKey+" ="+id);
		return delete.toString();
	}

	public String buildUpdateBatchSql(String[] ids) {
		StringBuilder delete=new  StringBuilder("update  "+tableName+" set status=0 where "+uniqueKey+" in (");
		for(int i=0;i<ids.length;i++){
			if(i==ids.length){
				delete.append(ids[i]);
			}else{
				delete.append(ids[i]+",");
			}
		}
		delete.append(")");
		return delete.toString();
	}

	public String buildDeleteBatchSql(String[] ids) {
		StringBuilder delete=new  StringBuilder("delete from "+tableName+" where "+uniqueKey+" in (");
		for(int i=0;i<ids.length;i++){
			if(i==ids.length){
				delete.append(ids[i]);
			}else{
				delete.append(ids[i]+",");
			}
		}
		delete.append(")");
		return delete.toString();
	}
	
	public Map<String,Object> describe(Object obj) throws Exception{
		Map<String,Object> map=Maps.newHashMap();
		Class<?> clazz = obj.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for (int i = 0; i < fields.length; i++) {
			if ((fields[i].getModifiers() & Modifier.STATIC) == 0) {
				if(fields[i].isAnnotationPresent(FieldBind.class)){
					map.put(fields[i].getAnnotation(FieldBind.class).fieldName(), fields[i].get(obj));
				}else{
					map.put(fields[i].getName(), ReflectUtil.getFieldValue(obj, fields[i].getName()));
				}
			}
		}
		return map;
	}
}
